package com.hundsun.yr.universal.p2p.utils;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import android.annotation.SuppressLint;
import android.util.Base64;

public class Des3Util {
	// 密钥 长度不得小于24
	private final static String secretKey = "51b94d28120d99dc7f8c5e701d8dfe55";
	// 向量 可有可无 终端后台也要约定
	private final static String iv = "b9243605";
	// 加解密统一使用的编码方式
	private final static String encoding = "utf-8";

	/**
	 * 3DES加密
	 * 
	 * @param plainText 普通文本
	 * @return
	 * @throws Exception
	 */
	@SuppressLint("TrulyRandom") 
	public static String encode(String plainText) {
		Key deskey = null;
		byte[] encryptData = null;
		
		try {
			DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
			SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
			deskey = keyfactory.generateSecret(spec);
			
			Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
			IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
			encryptData = cipher.doFinal(plainText.getBytes(encoding));
			
//			System.out.println(HexUtils.byte2hex(encryptData));
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return Base64.encodeToString(encryptData, Base64.DEFAULT);
	}

	/**
	 * 3DES解密
	 * 
	 * @param encryptText
	 *            加密文本
	 * @return
	 * @throws Exception
	 */
	public static String decode(String encryptText) {
		Key deskey = null;
		try {
			
			DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
			SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
			deskey = keyfactory.generateSecret(spec);
			Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
			IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
			
			byte[] decryptData = cipher.doFinal(Base64.decode(encryptText,
					Base64.DEFAULT));
			return new String(decryptData, encoding);
		} catch (Exception e) {
			// TODO: handle exception
			return "";
		}

	}
}
